<template>
	<view class="upload-file">
		<!-- 文件列表 -->
		
		<view v-if="!disabled">
			<l-file ref="filemanager" :logo="logo" @up-success="onSuccess" style="z-index: 99999;"></l-file>
			<u-button v-if="!isIcon" type="primary" style="z-index: 91;" size="medium" @click="uploadFile">上传文件</u-button>
			<u-icon v-else @click="uploadFile" :size="iconSize" :name="iconName" :color="iconColor"></u-icon>
		</view>
		<!-- 权限告知弹窗 -->
		<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup>
		<!-- <view class="files" v-if=" !isIcon && dataSource.length > 0">
			<view class="file" v-for="(item,index) in dataSource" :key="index">
				<view class="file-name" @click="upload(index)">{{item.fileName}}</view>
				<u-icon v-if="!disabled" @click="deleteFile(index)" size="30" class="btn-icon" name="trash-fill">
				</u-icon>
			</view>
		</view> -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>
<script>
	const getTokenStorage = () => {
		let token = ''
		try {
			token = uni.getStorageSync('ACCESS_TOKEN')
		} catch (e) {
			// error
		}
		return token
	}
	const getUserId = () => {
		let user_id = ''
		try{
			user_id = uni.getStorageSync('userInfo').id
		}catch(e){
			//TODO handle the exception
		}
		return user_id
	}
	import {
		BASE_URL
	} from '../../utils/baseUrl.js'
	import {
		UPLOAD
	} from '../../api/urls.js';
	export default {
		name: "uploadFile",
		model: {
			prop: 'files',
			event: 'change'
		},
		data() {
			return {
				BASE_URL,
				permissionID: 'WRITE_EXTERNAL_STORAGE',
				logo: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F00%2F07%2F155788a6d8a5c42.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619847627&t=2da40b583002205c204d980b54b35040',
				dataSource: [], //文件地址
			};
		},
		props: {
			files: {
				type: [String, Object],
				default: () => {}
			},
			disabled: {
				type: Boolean,
				default: false
			},
			isIcon: {
				type: Boolean,
				default: true
			},
			// 是否只上传单个
			isApproval: {
				type: Boolean,
				default: false
			},
			iconName: {
				default: 'attach'
			},
			iconColor: {
				default: '#1E6FFF'
			},
			iconSize: {
				default: 26
			}
		},
		methods: {
			openAuth(){
				this.$refs['authpup'].open() //调起自定义权限目的弹框,具体可看示例里面很详细
			},
			changeAuth () {
				
			},
			encodeURIForChinese(url) {
			    let chineseArray = url.match(/[^\x00-\xff]+/ig);
			    for (let i = chineseArray.length - 1; i >= 0; i--) {
			        url = url.replace(chineseArray[i], encodeURIComponent(chineseArray[i]));
			    }
			    return url;
			},
			//下载
			upload(index) {
				const _fileName = this.dataSource[index];
				var url = ''
				if(_fileName.indexOf('http')<=-1) {
					url = `${this.BASE_URL}/jeecg-system/sys/common/static/${_fileName}`
					
				} else {
					url = _fileName
				}
				url = url.replace(/([^\u0000-\u00FF])/g, function ($) { return encodeURI($)})
				// let url = `${this.BASE_URL}/jeecg-system/sys/common/static/${_fileName}`
				// return ;
				// #ifdef APP-PLUS
				plus.runtime.openURL(url,err=>{
					uni.showToast({
						title: '文件打开失败，可能已失效，或地址不存在',
						icon: 'none'
					})
				});
				// #endif
				return;
			},
			//删除
			deleteFile(index) {
				this.dataSource.splice(index, 1);
				this.$emit('change', this.dataSource);
			},
			uploadFile() {
				this.$refs.filemanager.upload({
					// #ifdef APP-PLUS
					//（app端必传）nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
					currentWebview: this.$mp.page.$getAppWebview(),
					// #endif
					//替换为你的上传接口地址
					url: this.BASE_URL + UPLOAD,
					// 服务端接收附件的key
					name: 'file',

					header: {
						'Authorization': getTokenStorage(),
						'client-id': 'app_erp',
						'user-id': getUserId()
					}

					// 限制选择附件的大小上限，默认10M
					// maxSize: 20,

					// 若需要在body单独添加附件名或附件大小如下方式传入组件：
					// addName: '后端要的附件名称字段key,此处请勿写name的同值如(file)，会覆盖name',
					// addSize: '后端要的附件大小字段key'

					// body参数直接写key,value,如：
					// date: '2020-1-1',
					// key2: 'value2',
				});
			},
			onSuccess(res) {
				// 是否只上传单个文件
				if (!this.isApproval) {
					this.dataSource = []
				}
				const _data = res.data;
				var fileSize = ''
				if (res.size > 314572800) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请上传500MB以内的文件",
						iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/default.png'
					})
					return false
				}
				// 判断文件的大小
				if (res.size >= 1024) {
					// 文件大于字节
					if (res.size / 1024 >=1024) {
						// 文件大于kb
						if (res.size / 1048576 >=1024) {
							// 文件大于mb
							fileSize = ((res.size / 1073741824).toFixed(2)) + 'GB'
						} else {
							// 文件小于1024mb
							fileSize = ((res.size / 1048576).toFixed(2)) + 'MB'
						}
					} else {
						// 文件小于1024kb
						fileSize = ((res.size / 1024).toFixed(2)) + 'KB'
					}
				} else {
					// 文件小于1024字节
					fileSize = res.size + 'B'
				}
				
				// 判断类型
				var typeFile = ''
				if (_data.message.indexOf('.') != -1) {
					var arr = _data.message.split('.')
					typeFile = '.' + arr[arr.length - 1]
				} else {
					typeFile = ''
				}
				
				if (_data.success) {
					var file = {
						fileName: _data.result,
						filePath: _data.message,
						size: fileSize,
						type: typeFile
					}
					this.dataSource.push(file);
					// this.$emit('change', this.dataSource);
					// if (!this.isIcon) {
						var filePath = ''
						if (this.files) {
							filePath = this.files
						} else {
							filePath = ''
						}
						
						this.dataSource.map(value => {
							filePath = value.filePath + ',' + filePath
						})
						if (!this.files) {
							filePath = filePath.substr(0,filePath.length-1)
						}
						
						this.$emit('change', filePath);
						
					// } else {
					// 	this.$emit('change', this.dataSource);
					// }
					uni.showToast({
						title: '上传成功',
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: _data.message,
						icon: 'none'
					})
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	.upload-file {
		width: 100%;
		height: auto;

		.files {
			width: 100%;
			margin-bottom: 14rpx;

			.file {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: #f4f5f6;
				padding: 10rpx;

				.file-name {
					flex: 1;
					word-break: break-all;
					line-height: 30rpx;
					font-size: 12px;
					margin-right: 14rpx;
					text-decoration: underline;
				}

				.btn-icon {
					padding: 10rpx 0 10rpx 10rpx;
				}
			}
		}
	}
</style>
